package ncme.auto.framework.core.dynamicDatasource.mybatisPlugin;

import ncme.auto.framework.core.dynamicDatasource.configs.DynamicDataSourceConfig;
import ncme.auto.framework.core.dynamicDatasource.entity.SqlConnectInfo;
import ncme.auto.framework.core.dynamicDatasource.utils.ConvertUtil;
import ncme.auto.framework.core.dynamicDatasource.utils.SQLExecutor;
import ncme.auto.framework.core.exceptions.AutoException;
import ncme.auto.framework.core.exceptions.ExceptionEnum;
import org.apache.ibatis.executor.resultset.ResultSetHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Properties;

@Component
@Intercepts(
        {
                @Signature(type = ResultSetHandler.class, method = "handleResultSets", args = java.sql.Statement.class)
        }
)
public class SelectResultPlugin extends SQLExecutor implements Interceptor {

    @Autowired
    private ConvertUtil convertUtil;

    @Autowired
    private DynamicDataSourceConfig dataSourceConfig;

    /*intercept拦截：拦截目标对象的目标方法的执行*/
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Object result;
        if (dataSourceConfig.changeSource) {
            try {
                //获取基本信息
                Object target = invocation.getTarget();
                MetaObject metaObject = SystemMetaObject.forObject(target);
                Class<?> entityClass = ((MappedStatement) metaObject.getValue("parameterHandler.mappedStatement")).getResultMaps().get(0).getType();
                Object parameter = metaObject.getValue("parameterHandler.parameterObject");
                String sql = ((BoundSql) metaObject.getValue("parameterHandler.boundSql")).getSql();
                //获取数据库连接信息
                SqlConnectInfo sqlConnectInfo = dataSourceConfig.getDataSourceInfo();
                //执行sql，包装结果
                List<String> parameters = convertUtil.getParamForSelect(parameter);
                sql = convertUtil.setSqlParameters(sql, parameters);
                Object originResult = executeSql(sqlConnectInfo, sql);
                result = convertUtil.wrapResult(entityClass, originResult);
            } catch (Exception e) {
                throw new AutoException(ExceptionEnum.JDBC, "mybatis插件错误 caused by: " + e.getMessage());
            }
        } else result = invocation.proceed();
        return result;
    }

    /*plugin：包装目标对象（为目标对象创建一个代理对象）*/
    @Override
    public Object plugin(Object target) {
        Object wrap = Plugin.wrap(target, this);
        return wrap;
    }

    //将插件注册时的property属性设置进来
    @Override
    public void setProperties(Properties properties) {

    }
}